package com.resifind.www.service.impl;

import com.resifind.www.constant.ErrorCode;
import com.resifind.www.dao.BrowseDao;
import com.resifind.www.dao.MerchantDao;
import com.resifind.www.dao.impl.BrowseDaoImpl;
import com.resifind.www.dao.impl.MerchantDaoImpl;
import com.resifind.www.exception.BaseException;
import com.resifind.www.exception.ClientException;
import com.resifind.www.exception.Resp;
import com.resifind.www.po.Browse;
import com.resifind.www.service.BrowseService;
import com.resifind.www.util.JdbcUtils;

import java.sql.Connection;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author 36069
 */
public class BrowseServiceImpl implements BrowseService {
    private final BrowseDao browseDao = new BrowseDaoImpl();
    private final MerchantDao merchantDao = new MerchantDaoImpl();

    @Override
    public Resp<List<Browse>> queryBrowseByClientId(int clientId) {
        List<Browse> browses = browseDao.queryBrowseByClientId(clientId);
        return Resp.success(browses);
    }

    @Override
    public Resp<String> addOrUpdateBrowse(int clientId, int merchantId) {
        // 判断客户id是否存在
        if (clientId <= 0) {
            throw ClientException.viewNotClient();
        }
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String time = now.format(formatter);
        // 用于检查是否已经存在该浏览记录
        Browse browse = browseDao.queryBrowseByClientIdAndMerchantId(clientId, merchantId);
        Connection conn = null;
        try {
            conn = JdbcUtils.getConn();
            JdbcUtils.beginTransaction(conn);
            boolean updateResult = true;
            boolean addResult = true;
            boolean updateMerchantResult = true;
            if (browse != null) {
                // 判断浏览记录时间与当前时间是否超过1分钟
                LocalDateTime browseTime = LocalDateTime.parse(browse.getTime(), formatter);
                if (now.minusMinutes(1).isAfter(browseTime)) {
                    // 更新商家浏览量
                    updateMerchantResult = merchantDao.updateViewCount(merchantId, conn);
                }
                // 更新时间
                updateResult = browseDao.updateBrowse(clientId, merchantId, time, conn);
            } else {
                // 如果不存在，添加新记录
                addResult = browseDao.addBrowse(clientId, merchantId, time, conn);
                // 更新商家浏览量
                updateMerchantResult = merchantDao.updateViewCount(merchantId, conn);
            }
            if (updateResult && addResult && updateMerchantResult) {
                JdbcUtils.commitTransaction(conn);
                return Resp.success("success");
            } else {
                JdbcUtils.rollbackTransaction(conn);
                throw new BaseException(ErrorCode.DB_ERROR);
            }
        } catch (BaseException e) {
            throw e;
        } catch (Exception e) {
            JdbcUtils.rollbackTransaction(conn);
            throw new BaseException(ErrorCode.SERVER_ERROR);
        } finally {
            JdbcUtils.closeConn(conn, null, null);
        }
    }

    @Override
    public Resp<String> deleteBrowse(int clientId, int merchantId) {
        Connection conn = null;
        try {
            conn = JdbcUtils.getConn();
            JdbcUtils.beginTransaction(conn);
            boolean result = browseDao.deleteBrowse(clientId, merchantId, conn);
            if (result) {
                JdbcUtils.commitTransaction(conn);
                return Resp.success("success");
            } else {
                JdbcUtils.rollbackTransaction(conn);
                throw new BaseException(ErrorCode.DB_ERROR);
            }
        } catch (BaseException e) {
            throw e;
        } catch (Exception e) {
            JdbcUtils.rollbackTransaction(conn);
            throw new BaseException(ErrorCode.SERVER_ERROR);
        } finally {
            JdbcUtils.closeConn(conn, null, null);
        }
    }

    @Override
    public Resp<String> clearBrowse(int clientId) {
        //查询是否存在该客户的浏览记录
        List<Browse> browseList = browseDao.queryBrowseByClientId(clientId);
        if (browseList.isEmpty()) {
            return Resp.success("success");
        }
        Connection conn = null;
        try {
            conn = JdbcUtils.getConn();
            JdbcUtils.beginTransaction(conn);
            boolean result = browseDao.clearBrowse(clientId, conn);
            if (result) {
                JdbcUtils.commitTransaction(conn);
                return Resp.success("success");
            } else {
                JdbcUtils.rollbackTransaction(conn);
                throw new BaseException(ErrorCode.DB_ERROR);
            }
        } catch (BaseException e) {
            throw e;
        } catch (Exception e) {
            JdbcUtils.rollbackTransaction(conn);
            throw new BaseException(ErrorCode.SERVER_ERROR);
        } finally {
            JdbcUtils.closeConn(conn, null, null);
        }
    }
}
